package approvalDaoImplement;

import approvalDao.ConnectionFactory;
import approvalDao.Information;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

@WebServlet(name = "FeedbackServlet", value = "/FeedbackServlet")
public class FeedbackServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //response.setCharacterEncoding("UTF-8");
        //response.setContentType("text/html;charset=UTF-8");
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        InputStreamReader inputStreamReader = new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8);
        PrintWriter out=response.getWriter();
        StringBuilder str = new StringBuilder();
        int respInt = inputStreamReader.read();
        while (respInt!=-1){
            str.append((char) respInt);
            respInt = inputStreamReader.read();
        }
        String jsonString =String.valueOf(str);
        JSONObject jsonObject = JSON.parseObject(jsonString);
        String string = jsonObject.getString("username");
        String userName = JSON.toJSONString(string);


        Connection connection = ConnectionFactory.getConnection();
        Statement statement = null;
        ResultSet resultSet = null;
        String sql = "SELECT `status` FROM borrowrecord WHERE `username` = "+userName+";";
        //String sql = "SELECT `status` FROM borrowrecord WHERE `username` = 'zhangshuai';";
        try {
            statement = connection.createStatement();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            resultSet = statement.executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        String status = null;
        try {
            status = resultSet.getString("status");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        String message = JSON.toJSONString(Information.Feedback(status));
        out.println(message);

    }
}
